package com.miracle.common.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.miracle.basemvp.base.BaseResponse;
import com.miracle.basemvp.lifecycle.rx.RxDefaultObserver;
import com.miracle.common.R;
import com.miracle.common.mvp.entity.response.BaseListResponse;
import com.miracle.common.util.CommonConstants;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * com.miracle.common.view
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/18 19:00
 * @see com.miracle.common.view
 */
public class RefreshView<T, M> extends LinearLayout implements OnLoadmoreListener,
        OnRefreshListener {
    private Context mContext;
    private SmartRefreshLayout mSmartRefreshLayout;
    private RefreshViewListener mRefreshListener;

    private RecyclerView.Adapter mAdapter;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    /**
     * 加载布局
     */
    private LinearLayout mLoadingLayout;
    /**
     * 状态布局（无数据、无网络）
     */
    private LinearLayout mStateLayout;

    private List<T> mArrayList;


    /**
     * 是否是加载更多
     */
    private boolean mIsLoadMore = false;
    private int mCurrPage = CommonConstants.Page.FIRST_PAGE;
    private int mPageSize = CommonConstants.Page.PAGE_SIZE_A;

    public RefreshView(Context context, List<T> arraylist, RecyclerView.Adapter adapter) {
        super(context);
        this.mArrayList = arraylist;
        this.mAdapter = adapter;
        mContext = context;
        init();
    }

    /**
     * 初始化视图，控件
     */
    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_refresh, this);
        mSmartRefreshLayout = view.findViewById(R.id.smr);
        mRecyclerView = view.findViewById(R.id.rv);
        mStateLayout = view.findViewById(R.id.ll_no_data_file_list);
        mSmartRefreshLayout.setOnLoadmoreListener(this);
        mSmartRefreshLayout.setOnRefreshListener(this);
        mLayoutManager = new LinearLayoutManager(mContext);

        listObserver = new
                RxDefaultObserver<BaseResponse<BaseListResponse<T>>>(mContext) {

                    @Override
                    public void onSucceed(BaseResponse<BaseListResponse<T>> arrayListBaseResponse) {
                        RefreshView.this.onComplete(arrayListBaseResponse, arrayListBaseResponse
                                .getContent().getList());
                    }
                };
    }

    /**
     * 设置监听器
     * @param listener
     */
    public void setmRefreshListener(RefreshViewListener listener) {
        mRefreshListener = listener;
    }

    /**
     * 开始请求数据
     */
    public void onStart() {
        if (mRefreshListener != null) {
            mRefreshListener.onRequestData();
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrPage++;
        mIsLoadMore = true;
        mRefreshListener.onRequestData();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrPage = CommonConstants.Page.FIRST_PAGE;
        mIsLoadMore = false;
        mRefreshListener.onRequestData();
    }

    /**
     * 设置布局manager
     * @param layoutManager
     */
    public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
        mLayoutManager = layoutManager;
    }

    /**
     * 设置适配器
     * @param adapter
     */
    public void setAdapter(RecyclerView.Adapter adapter) {
        mAdapter = adapter;
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
    }

    /**
     * 设置一页加载数量，默认为 CommonConstants.Page.PAGE_SIZE_A
     * @param pageSize 数量
     */
    public void setPageSize(int pageSize) {
        mPageSize = pageSize;
    }

    /**
     * 加载更多成功，填充数据
     * @param list
     */
    public void loadMoreSucc(List<T> list) {
        mArrayList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 刷新成功，填充数据
     * @param list
     */
    public void getListSucc(List<T> list) {
        mArrayList.clear();
        mArrayList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 请求成功后，如果格式合适，可以直接调用接口，免去其他判断
     * @param baseResponse
     * @param list
     */
    public void onComplete(BaseResponse baseResponse, List<T> list) {
        if (baseResponse.getContent() != null && list != null && list.size() > 0) {
            if (list.size() < mPageSize) {
                onNoLoadMoreState();
            } else {
                onSuccessState();
            }
            if (getIsLoadMore()) {
                loadMoreSucc(list);
            } else {
                getListSucc(list);
            }
        } else {
            if (getIsLoadMore()) {
                onNoLoadMoreState();
            } else {
                onNoDataState();
            }
        }
    }

    /**
     * 无数据状态
     */
    public void onNoDataState() {
        Log.d("WJQ", "onNoDataState");
        setLoadingState(false);
        closeSmartRefreshLayout();
        setStateLayoutVisiable(View.VISIBLE);
        setStateText(true);
        setStateRes(true);
    }

    public void onErrorState(String errorMsg) {
        Log.d("WJQ", "onErrorState: " + errorMsg);
        setLoadingState(false);
        closeSmartRefreshLayout();
        setStateLayoutVisiable(View.VISIBLE);
        setStateText(false);
        setStateRes(false);
    }

    public void onSuccessState() {
        closeSmartRefreshLayout();
        setStateLayoutVisiable(View.GONE);
        setLoadingState(false);
    }

    /**
     * 没有更多数据
     */
    public void onNoLoadMoreState() {
        onSuccessState();
        if (mSmartRefreshLayout != null) {
            mSmartRefreshLayout.finishLoadmoreWithNoMoreData();
        }
    }

    /**
     * 关闭刷新布局
     */
    private void closeSmartRefreshLayout() {
        if (mSmartRefreshLayout != null) {
            //关闭刷新
            mSmartRefreshLayout.finishRefresh();
            //关闭加载更多
            mSmartRefreshLayout.finishLoadmore();
        }
    }


    /**
     * 设置状态布局可见性
     * @param visiable {@link }
     */
    private void setStateLayoutVisiable(int visiable) {
        if (mStateLayout != null) {
            mStateLayout.setVisibility(visiable);
        }
    }

    /**
     * 设置刷新状态
     * @param isLoading
     */
    private void setLoadingState(boolean isLoading) {
        if (mLoadingLayout == null) {
            return;
        }

        if (isLoading) {
            mLoadingLayout.setVisibility(View.VISIBLE);
        } else {
            mLoadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置状态图片
     * @param isNodaState 是无数据状态
     */
    private void setStateRes(boolean isNodaState) {
//        if (isNodaState) {
//            if (stateIv != null) {
//                stateIv.setImageResource((noDataRes != 0) ? noDataRes : RES_NODATA);
//            }
//        } else {
//            if (stateIv != null) {
//                stateIv.setImageResource((errorRes != 0) ? errorRes : RES_ERROR);
//            }
//        }
    }

    /**
     * 设置状态文字
     * @param isNodaState 是无数据状态
     */
    private void setStateText(boolean isNodaState) {
//        if (isNodaState) {
//            if (stateTv != null) {
//                stateTv.setText((TextUtils.isEmpty(noDataMsg) ? MSG_NODATA : noDataMsg));
//            }
//        } else {
//            if (stateTv != null) {
//                stateTv.setText((TextUtils.isEmpty(noDataMsg) ? MSG_ERROR : errorMsg));
//            }
//        }
    }


    /**
     * 获取是否为加载更多
     * @return 是否为加载更多
     */
    public boolean getIsLoadMore() {
        return mIsLoadMore;
    }

    /**
     * 获取当前页数
     * @return
     */
    public int getCurrPage() {
        return mCurrPage;
    }

    /**
     * 返回每页加载数量
     * @return
     */
    public int getPageSize() {
        return mPageSize;
    }

    public RxDefaultObserver<BaseResponse<ArrayList<T>>> getObserVer() {
        return null;
    }

    public RxDefaultObserver<BaseResponse<BaseListResponse<T>>> getListObserVer() {
        return listObserver;
    }

    /**
     * 目前格式局限
     */
    RxDefaultObserver<BaseResponse<BaseListResponse<T>>> listObserver;
    /**
     * 目前格式局限
     */
    RxDefaultObserver<BaseResponse<M>> observer = new
            RxDefaultObserver<BaseResponse<M>>(mContext) {


                @Override
                public void onSucceed(BaseResponse<M> arrayListBaseResponse) {
                    mRefreshListener.observerCallback(arrayListBaseResponse, RefreshView.this);
                }
            };


    public interface RefreshViewListener<M> {
        /**
         * 开始请求数据
         */
        void onRequestData();

        void observerCallback(BaseResponse<M> baseResponse, RefreshView<M,Object> refreshView);
    }
}
